package com.ttn.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ttn.business.service.CourseUnitService;
import com.ttn.common.core.entity.PageQuery;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.business.CourseUnit;
import com.ttn.common.core.entity.business.bo.ModifyCourseUnitSortBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 题库管理(StudentRecord)表控制层
 *
 * @author makejava
 * @since 2023-01-30 15:57:40
 */
@RestController
@Slf4j
@RequestMapping("course-unit")
public class CourseUnitController {
    /**
     * 服务对象
     */
    @Resource
    private CourseUnitService courseUnitService;


    /**
     * 新建题库
     *
     * @param request
     * @param courseUnit
     * @return
     */
    @PostMapping("/save/course-unit")
    public Result saveCourseUnit(HttpServletRequest request, @RequestBody CourseUnit courseUnit) {
        log.info("CourseUnitController saveCourseUnit ,参数:{}", courseUnit);
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper();
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, courseUnit.getGrade());
        courseUnit.setSort(Math.toIntExact(courseUnitService.count(courseUnitLambdaQueryWrapper)) + 1);
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getCourseUnitName, courseUnit.getCourseUnitName());
        //判断等级名称是否重复。不重重则直接保存
        if (courseUnitService.count(courseUnitLambdaQueryWrapper) > 0) {
            return Result.fail("单元名称重复,请确认后重试");
        }
        courseUnitService.save(courseUnit);
        return Result.success();
    }

    /**
     * 修改题库信息
     *
     * @param request
     * @param courseUnit
     * @return
     */
    @PutMapping("/modify/course-unit")
    public Result modifyCourseUnit(HttpServletRequest request, @RequestBody CourseUnit courseUnit) {
        log.info("CourseUnitController modifyCourseUnit ,参数:{}", courseUnit);
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper();
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getCourseUnitName, courseUnit.getCourseUnitName());
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, courseUnit.getGrade());
        courseUnitLambdaQueryWrapper.ne(CourseUnit::getId, courseUnit.getId());
        //判断题库名称是否重复。不重重则直接保存
        if (courseUnitService.count(courseUnitLambdaQueryWrapper) > 0) {
            return Result.fail("单元名称重复,请确认后重试");
        }
        courseUnitService.updateById(courseUnit);
        return Result.success();
    }

    /**
     * 修改排序
     *
     * @param request
     * @param modifyCourseUnitSortBO
     * @return
     */
    @PutMapping("/modify/course-unit-sort")
    public Result modifyCourseUnitSort(HttpServletRequest request, @RequestBody ModifyCourseUnitSortBO modifyCourseUnitSortBO) {
        log.info("CourseUnitController modifyCourseUnitSort ,参数:{}", modifyCourseUnitSortBO);
        CourseUnit courseUnit = courseUnitService.getById(modifyCourseUnitSortBO.getId());
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper();
        courseUnitLambdaQueryWrapper.ne(CourseUnit::getId, modifyCourseUnitSortBO.getId());
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, courseUnit.getGrade());
        courseUnitLambdaQueryWrapper.orderByAsc(CourseUnit::getSort);
        List<CourseUnit> courseUnitList = courseUnitService.list(courseUnitLambdaQueryWrapper);
        if (courseUnitList.size() > 0) {
            int sortIndex = 0;
            if (modifyCourseUnitSortBO.getSortingBehavior().equals(-1)) {
                if (courseUnit.getSort() - 2 > 0) {
                    sortIndex = courseUnit.getSort() - 2;
                }
            } else if (modifyCourseUnitSortBO.getSortingBehavior().equals(1)) {
                sortIndex = courseUnit.getSort();
            }
            courseUnitList.add(sortIndex, courseUnit);
            AtomicInteger i = new AtomicInteger(1);
            courseUnitList.stream().forEach(courseUnit1 -> {
                courseUnit1.setSort(i.getAndIncrement());
            });
            courseUnitService.updateBatchById(courseUnitList);
        }
        return Result.success();
    }

    /**
     * 删除单元课程
     *
     * @param request
     * @param id
     * @return
     */
    @DeleteMapping("/delete/course-unit-by-id/{id}")
    public Result deleteCourseUnit(HttpServletRequest request, @PathVariable("id") Integer id) {
        log.info("CourseUnitController deleteCourseUnit ,参数id:{}", id);
        CourseUnit courseUnit = courseUnitService.getById(id);
        courseUnitService.removeById(id);
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper();
        courseUnitLambdaQueryWrapper.ne(CourseUnit::getId, id);
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, courseUnit.getGrade());
        courseUnitLambdaQueryWrapper.orderByAsc(CourseUnit::getSort);
        List<CourseUnit> courseUnitList = courseUnitService.list(courseUnitLambdaQueryWrapper);
        if (courseUnitList.size() > 0) {
            AtomicInteger i = new AtomicInteger(1);
            courseUnitList.stream().forEach(courseUnit1 -> {
                courseUnit1.setSort(i.getAndIncrement());
            });
            courseUnitService.updateBatchById(courseUnitList);
        }
        return Result.success();
    }

    /**
     * 通过级别id，获取响应课程
     *
     * @param request
     * @param gradeId
     * @param pageQuery
     * @return
     */
    @PostMapping("/query/course-unit-by-grade-page/{gradeId}")
    public Result queryCourseUnitByGradePage(HttpServletRequest request, @PathVariable("gradeId") Integer gradeId, @RequestBody PageQuery pageQuery) {
        log.info("CourseUnitController queryCourseUnitByGradePage ,参数gradeId:{},pageQuery:{}", gradeId, pageQuery);
        IPage<CourseUnit> courseUnitIPage = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, gradeId);
        courseUnitLambdaQueryWrapper.orderByAsc(CourseUnit::getSort);
        return Result.success(courseUnitService.page(courseUnitIPage, courseUnitLambdaQueryWrapper));
    }

    /**
     * @param gradeId
     * @return
     */

    @GetMapping("/service/query/course-unit-by-grade/{gradeId}")
    public Result serviceQueryCourseUnitByGrade(@PathVariable("gradeId") Integer gradeId) {
        log.info("CourseUnitController serviceQueryCourseUnitByGradePage ,参数gradeId:{}", gradeId);
//        IPage<CourseUnit> courseUnitIPage = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseUnitLambdaQueryWrapper.eq(CourseUnit::getGrade, gradeId);
        courseUnitLambdaQueryWrapper.orderByAsc(CourseUnit::getSort);
        return Result.success(courseUnitService.list(courseUnitLambdaQueryWrapper));
    }

    @GetMapping("/service/query/course-unit-number-by-grade/{gradeId}")
    public Result serviceQueryCourseUnitNumberByGrade(@PathVariable("gradeId") Integer gradeId) {
        log.info("CourseUnitController serviceQueryCourseUnitNumberByGrade ,参数gradeId:{}", gradeId);
        return courseUnitService.serviceQueryCourseUnitNumberByGrade(gradeId);
    }

    @GetMapping("/service/query/questions-number-by-unitId/{unitId}")
    Result<Integer> serviceQueryQuestionsNumberByUnitId(@PathVariable("unitId") Integer unitId) {
        log.info("CourseUnitController serviceQueryQuestionsNumberByUnitId ,参数unitId:{}", unitId);

        return courseUnitService.serviceQueryQuestionsNumberByUnitId(unitId);
    }

    @GetMapping("/service/query/course-unit-by-unit-id/{unitId}")
    public Result serviceQueryCourseUnitByUnitId(@PathVariable("unitId") Integer unitId) {
        log.info("CourseUnitController serviceQueryCourseUnitByUnitId ,参数unitId:{}", unitId);
        return Result.success(courseUnitService.getById(unitId));
    }


    /**
     * 获取课程里面的级别
     *
     * @param request
     * @param pageQuery
     * @return
     */
    @PostMapping("/query/course-unit-for-grade-page")
    public Result queryCourseUnitForGradePage(HttpServletRequest request, @RequestBody PageQuery pageQuery) {
        log.info("CourseUnitController queryCourseUnitForGradePage ,参数pageQuery:{}", pageQuery);
        LambdaQueryWrapper<CourseUnit> courseUnitLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseUnitLambdaQueryWrapper.orderByAsc(CourseUnit::getSort);
        return courseUnitService.queryCourseUnitForGradePage(pageQuery);
    }

    /**
     * 查看课程详情
     *
     * @param request
     * @param id
     * @return
     */
    @PostMapping("/query/course-unit-by-id/{id}")
    public Result queryCourseUnitById(HttpServletRequest request, @PathVariable("id") Integer id) {
        log.info("CourseUnitController queryCourseUnitById ,参数id:{}", id);
        return courseUnitService.queryCourseUnitById(id);
    }
}

